package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManageApi;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.content.common.feign.GetTokenFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class FileManageController implements FileManageApi {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private GetTokenFeign getTokenFeign;

    /*
    * #文件系统微服的请求地址
        file.service.url = http://127.0.0.1:56082
        #文件存储空间名称
        file.service.bucket = xczx123-static-imgs
        #文件存储区域的地址
        file.service.upload.region = http://upload-z1.qiniu.com
        #文件访问的cdn加速域名
        cdn.domain = qsrm3mr4y.hb-bkt.clouddn.com
    *
    * */
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;

    @GetMapping("/common/qnUploadToken")
    public Map<String, Object> upLoadImagesToken() {

        String fileUrl = url + "/farming/generatetoken?origin=qiniu";
        HashMap<String, Object> dataMap = new HashMap<>();

        /*
        * {
              "tokenType":"1",
              "scope":"xczx123-static-imgs",
              "deadline":3600
              "key":"111xxxeeee"
            }
        * */
        dataMap.put("tokenType","1");
        dataMap.put("scope",bucket);
        dataMap.put("deadline",3600);
        String fileKey = UUID.randomUUID().toString()+ RandomStringUtils.randomAlphanumeric(32);
        dataMap.put("key",fileKey);

       // ResponseEntity<Map> resultEntity = restTemplate.postForEntity(fileUrl, dataMap, Map.class);

        RestResponse<String> qiniu = getTokenFeign.generateToken("qiniu", dataMap);

        String result = qiniu.getResult();


       // Map body = resultEntity.getBody();
     //   Object token = body.get("result");

        dataMap.put("qnToken", result);
        dataMap.put("up_region", region);
        dataMap.put("domain", domain);
        return dataMap;
    }
}
